/*
 * Copyright 2013 Rivaldo.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jety.client;

import org.jety.client.transport.AsynchronousTransport;
import com.google.gson.JsonObject;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jety.commons.domain.HandlerManager;
import org.jety.commons.exception.AsynchronousException;
import org.jety.commons.util.AsynchronousUtil;
import org.jety.commons.util.CommunicationUtil;
import org.jety.commons.domain.JsonRpcMethod;

/**
 *
 * @author Rivaldo
 */
public class AsynchronousExecutor {

    private ExecutorService threadPoll;
    private HandlerManager handlerManager;

    public AsynchronousExecutor() {
        this.handlerManager = new HandlerManager();
        this.threadPoll = Executors.newCachedThreadPool();
    }

    public void addHandler(String name, Method method, Object[] params) throws AsynchronousException {

        boolean hasCallback = false;
        Class<?>[] types = method.getParameterTypes();

        for (int i = 0; i < types.length; i++) {

            if (AsynchronousUtil.isCallback(types[i])) {
                hasCallback = true;
                handlerManager.addGenericHandler(name, params[i], types[i]);
            }
        }

        if (!hasCallback) {
            throw new AsynchronousException("No callback parameter found.");
        }
    }

    public void addListner(AsynchronousTransport asyncTransport) {
        threadPoll.execute(asyncTransport);
    }

    public void execute(JsonObject callbackRequest) {

        try {
            JsonRpcMethod method = null;

            method = CommunicationUtil.getRequestMethod(callbackRequest);
            Method handlerMethod = handlerManager.getHandlerMethod(method);

            Object[] parameters = method.getTypedParams(handlerMethod);

            handlerMethod.invoke(handlerManager.getHandler(method), parameters);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(AsynchronousExecutor.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalArgumentException ex) {
            Logger.getLogger(AsynchronousExecutor.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvocationTargetException ex) {
            Logger.getLogger(AsynchronousExecutor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
